package com.gopay.bis.web.controller.expay;

import java.math.BigDecimal;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.bis.common.util.TransUtils;
import com.gopay.bis.domain.order.OrderInfo;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.UmPayConstants;
import com.gopay.common.domain.bank.ExPayBaseMessage;
import com.gopay.common.domain.bank.umpay.mtpay.UmPayMtPayMessage;

@Controller
@Scope("prototype")
public class UmPayMtPayServerRes extends ExPayBankResBase {
	private static Log logger = LogFactory.getLog(UmPayMtPayServerRes.class);

	@RequestMapping(value = "/umPayMtPayServerRes")
	protected ModelAndView execute(HttpServletRequest request,
			HttpServletResponse response) {
		logger.error("--------------- UmPayMtPayServerRes bankback  ---------------");
		return super.execute(request, response);
	}

	@Override
	protected ExPayBaseMessage buildMessage(HttpServletRequest request) {
		// 生产UMPAY平台验签对象
		Map<String, String> ht = new HashMap<String, String>();
        String name = "";
        String value = "";
        for (Enumeration names = request.getParameterNames(); names.hasMoreElements(); ht.put(name, value)) {
            name = (String) names.nextElement();
            value = request.getParameter(name);
        }
        
		if (ht == null || ht.size() == 0) {
			logger.error("联动优势信用卡无卡通知报文为NULL");
			return null;
		}

		UmPayMtPayMessage mtMsg = new UmPayMtPayMessage();
		mtMsg.setBank(BankConstants.BANK_LOGO_UMPAY);
		mtMsg.setBankBusProd(BisBankBusinessProd._05);
		mtMsg.setReqMap(ht);
		mtMsg.setBankOrderId(request.getParameter("order_id"));
		mtMsg.setOrderId(request.getParameter("order_id"));
		mtMsg.setAmount(new BigDecimal(request.getParameter("amount")));
		mtMsg.setTradeState(request.getParameter("trade_state"));
		return mtMsg;
	}

	@Override
	protected OrderInfo buildOrderInfo(HttpServletRequest request, Result result) {
		logger.error("UMPAY SERVER:"
				+ ToStringBuilder.reflectionToString((UmPayMtPayMessage) result
						.getModel("res")));
		OrderInfo orderInfo = new OrderInfo();
		// 后台通知，则发送联动平台响应
		UmPayMtPayMessage umpMessage = (UmPayMtPayMessage) result.getModel("res");
		if (umpMessage != null) {
			String umpResponse1 = umpMessage.getSign(); // 响应UMPAY平台字符串
			// 响应UMPAY平台信息需加入meta标签
			String umpResponse = "<META NAME=" + "\"MobilePayPlatform\""
					+ " CONTENT=\"" + umpResponse1 + "\">";
			String trade_state = request.getParameter("trade_state");
			String amt = TransUtils.amountConvert2Yuan(request
					.getParameter("amount"));
			if (trade_state != null
					&& trade_state.equals(UmPayConstants.TRADE_SUCCESS)) {
				orderInfo.setOrderId(umpMessage.getOrderId());// 为了获取系统订单号
				orderInfo.setAmt(amt);
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("00");
				orderInfo.setRetCode("00");
                orderInfo.setSpecial(umpResponse);
			} else {
				orderInfo.setOrderId(umpMessage.getOrderId());// 为了获取系统订单号
				orderInfo.setAmt(amt);
				orderInfo.setNotifyNum("1");
				orderInfo.setPayStatus("01");
				orderInfo.setRetCode("01");
				orderInfo.setRetMsg("");
			}
		}
		orderInfo.setCardType("");// 信用卡类型
		orderInfo.setIsNotify(true);
		orderInfo.setBankName("umpay");
		return orderInfo;
	}

	@Override
	protected boolean checkParameters(HttpServletRequest request) {
		if (StringUtils.isEmpty(request.getParameter("order_id"))
				|| StringUtils.isEmpty(request.getParameter("amount"))
				|| StringUtils.isEmpty(request.getParameter("trade_state"))) {
			return false;
		}
		return true;
	}

	/**
	 * 金额格式转换 100 --> 1.00
	 * 
	 * @param amtStr
	 * @return
	 */
	protected String formatAmt(String amtStr) {

		// 增加校验功能，防止误操作
		if (amtStr.indexOf(".") > -1) {
			return amtStr;
		}

		BigDecimal amt = null;
		try {
			amt = new BigDecimal(amtStr);
		} catch (Exception e) {
			logger.error("订单金额不能转换为数字：" + amtStr, e);
			amt = new BigDecimal("0");
		}
		amt = amt.movePointLeft(2);
		return amt.toString();
	}
}
